'''
功能：剪切视频并保留原始视频修改时间
运行方式：
python cutvideo.py 视频路径 03:02 01:04:01
剪切视频：03分02秒~01时04分01秒
'''

import time, os, sys
from moviepy.editor import VideoFileClip
sys.path.append(os.path.dirname(__file__))
from modify_file_time import get_file_time, change_file_time
from hos import OSrep_name, OSname
from common import argv_files


class MovieCut:
    def __init__(self, path):
        self.path = path
        self.vid = VideoFileClip(self.path, target_resolution=None)
        # 获取原始宽高比
        self.aspect_ratio = self.vid.aspect_ratio
        print(self.aspect_ratio)
        # 手机竖屏拍摄时使用：
        if '--ver' in sys.argv:
            self.vid = self.vid.resize((self.vid.size[1], self.vid.size[0]))
    
    def mTime(self, t):
        '''
            传入视频时间：
                03:25 (3分25秒)，01:03:05（1时3分25秒）
            返回秒数
        '''
        l = t.split(':')
        min, sec = l[-2], l[-1]
        hour = 0 if(len(l))<3 else l[0]
        return int(hour)*3600+int(min)*60+int(sec)
    
    def cut(self, save_path, start=None, end=None):
        if not start:
            start=0
        else:
            start= self.mTime(start)
        if not end:
            end = self.vid.duration
        else:
            end = self.mTime(end)
        clipped_video = self.vid.subclip(start, end)
        # 导出视频
        clipped_video.write_videofile(save_path)
        
    def close(self):
        self.vid.close()
       

def main():
    start, end = None, None
    if len(sys.argv)>2:
        start = sys.argv[2]
    if len(sys.argv)>3:
        end = sys.argv[3]
    for path in argv_files():
        mc = MovieCut(path)
        save_path = OSrep_name(path, OSname(path)+"_output.mp4")
        create, modify, access = get_file_time(path)
        mc.cut(save_path, start, end)
        mc.close()
        change_file_time(save_path, create, modify, access)
        print("剪切完成")


if __name__=="__main__":
    main()
